package weekthree;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;

public class NNodeTreeLevelOrder_429 {
    public List<List<Integer>> levelOrder(Node root) {
        List<List<Integer>> list = new ArrayList<List<Integer>>();
        Queue<Node> queue = new LinkedList<Node>();
        if (root != null) queue.offer(root);
        while (!queue.isEmpty()) {
            int levelNodeSum = queue.size();
            List<Integer> row = new ArrayList<Integer>();
            for (int i = 0; i < levelNodeSum; i++) {
                Node node = queue.poll();
                row.add(node.val);
                for (Node nextLevelNode : node.children) {
                    queue.offer(nextLevelNode);
                }

            }
            list.add(row);
        }
        return list;
    }

    public List<List<Integer>> levelOrderWithPair(Node root) {
        List<List<Integer>> list = new ArrayList<List<Integer>>();
        Queue<Pair<Node, Integer>> queue = new LinkedList<Pair<Node, Integer>>();
        if(root!=null)queue.offer(new Pair(root, 0));
        while(!queue.isEmpty()){
            Pair<Node, Integer> pair = queue.poll();
            int depth = pair.getValue();
            if(list.size()<=depth){
                list.add(new ArrayList<Integer>());
            }
            list.get(depth).add(pair.getKey().val);
            for(Node nextLevelNode : pair.getKey().children){
                queue.offer(new Pair(nextLevelNode, depth+1));
            }

        }
        return list;
    }

    private class Node{
        public int val;
        public List<Node> children;

        public Node() {}

        public Node(int _val) {
            val = _val;
        }

        public Node(int _val, List<Node> _children) {
            val = _val;
            children = _children;
        }
    }

    private class Pair<Node, Integer> {
        private Node key;
        private int value;

        public Pair(Node key, int value) {
            this.key = key;
            this.value = value;
        }

        public Node getKey() {
            return key;
        }

        public int getValue() {
            return value;
        }
    }
}
